package com.af.system.Utils;

import org.springframework.util.Base64Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author : zhenyun.su
 * @since : 2019/12/03
 * @comment : 编码工具
 * 环境要求： Base64 依赖 tomcat-embed-servlet-9.0.22.jar，来自己spring boot 内嵌tomcat
 * 提供方法：
 * 1 将字节码转换为十六进制字符串:   static String HexString(byte[] byteBuffer)
 * 2 将字节码转换为Base64编码字符串：static String Base64String(byte[] byteBuffer)
 * 3 将字符串按UTF-8编码转换为URLEncode编码：
 * static String UrlEncodeString(String value) throws UnsupportedEncodingException
 * @See SignUtils
 */

public final class AfEncodeUtils {
    /**
     * @Comment: 将字节码转换为十六进制字符串
     */
    public static String HexString(byte[] byteBuffer) {
        StringBuffer strHex = new StringBuffer();
        for (int i = 0; i < byteBuffer.length; i++) {
            String hex = Integer.toHexString(0xff & byteBuffer[i]);
            if (hex.length() == 1) {
                strHex.append('0');
            }
            strHex.append(hex);
        }
        return strHex.toString();
    }

    // 比较上面方法，不同
    public static String toHex(byte hash[]) {
        if (hash == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    /**
     * @Comment: 将字节码转换为Base64编码字符串
     */
    public static String Base64String(byte[] byteBuffer) {
        return Base64Utils.encodeToString(byteBuffer);
//        return new String(Base64.encodeBase64(byteBuffer));
        //依赖 org.apache.tomcat.util.codec.binary.Base64;
    }
    /**
     * @Comment: 将字符串按UTF-8编码转换为URLEncode编码
     */
    public static String toUrlEncode(String value) throws UnsupportedEncodingException {
        return URLEncoder.encode(value, "UTF-8");
    }

    /**
     * @Comment: 将URLEncode编码按UTF-8编码解码为字符串
     */
    public static String UrlDecodeString(String value) throws UnsupportedEncodingException {
        return URLDecoder.decode(value, "UTF-8");
    }
}
